package com.cbh.amadeus.client.factory;

import com.cbh.amadeus.client.domain.MessageRepositoryModel;
import com.cbh.amadeus.client.receiver.tool.MessageRepositoryModelTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;

import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author ChenBiHui
 * @date 2025/5/23
 */
@Slf4j
public class MessageAbandonFactory implements InitializingBean {

    private static final LinkedBlockingQueue<MessageRepositoryModel> ABANDON_QUEUE = new LinkedBlockingQueue<>();

    private final MessageRepositoryModelTool tool;

    public MessageAbandonFactory(MessageRepositoryModelTool tool) {
        this.tool = tool;
    }

    public static void put(MessageRepositoryModel model) {
        ABANDON_QUEUE.offer(model);
    }

    @Override
    public void afterPropertiesSet() {
        Thread delay = new Thread(() -> {
            while (true) {
                try {
                    MessageRepositoryModel take = ABANDON_QUEUE.take();
                    tool.adjust(take.getTopic(), take.getMessageId(), MessageRepositoryModel.MessageRepositoryEnum.ABANDON);
                } catch (Throwable e) {
                    log.error(e.getMessage(), e);
                }
            }
        });
        delay.setName("amadeus-message-abandon");
        delay.setDaemon(true);
        delay.start();
        log.info("===== AmadeusMessageAbandon started =====");
    }
}
